#include <string.h>
#include <scos.h>

void MAIN(void)
{
	SOCKET a, b, c;
	struct sockaddr addr1, addr2, addr3;
	int namelen;
	char buf[6];

	scos_init();

	printf("Making addresses\n");

	addr1.sa_family = AF_UNIX;
	strcpy(addr1.sa_data, "/tmp/socket1");
	addr2.sa_family = AF_UNIX;
	strcpy(addr2.sa_data, "/tmp/socket2");

	printf("Creating and binding sockets\n");

	if ((a = scos_socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
		printf("Couldn't get client socket: %d\n", errno);
	if (scos_bind(a, &addr1, strlen(addr1.sa_data)+sizeof(addr1.sa_family)) < 0)
		printf("Couldn't bind client socket\n");

	if ((b = scos_socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
		printf("Couldn't get server socket\n");
	if (scos_bind(b, &addr2, strlen(addr2.sa_data)+sizeof(addr2.sa_family)) < 0)
		printf("Couldn't bind server socket\n");

	printf("Setting up connection\n");

	if (scos_listen(b, 5) < 0)
		printf("Couldn't listen to server socket\n");
	if (scos_connect(a, &addr2, strlen(addr2.sa_data)+sizeof(addr2.sa_family)) < 0)
		printf("Couldn't connect to server socket\n");
	if ((c = scos_accept(b, &addr3, &namelen)) < 0)
		printf("Couldn't accept client connection\n");
	if (!strcmp(addr1.sa_data, addr3.sa_data))
		printf("Wrong client address\n");

	printf("Writing data\n");

	if (scos_send(a, "test!", 6, 0) < 6)
		printf("Couldn't send data to server\n");
	if (scos_recv(c, buf, 6, 0) < 6)
		printf("Couldn't receive data from client\n");

	if (strcmp("test!", buf))
		printf("Wrong data: \"%s\"\n", buf);

	printf("Closing sockets\n");

	scos_close(a);
	scos_close(b);
	scos_close(c);
}
